<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>

    var socket;

    // 判断当前浏览器是否支持websocket
    if (window.WebSocket) {
        // 建立连接
        socket = new WebSocket("ws://localhost:7000/hello");

        // 相当于channelRead0
        socket.onmessage = function (even) {
            var rt = document.getElementById('responseBody');
            rt.value = rt.value + "\n" + even.data;
        }
        // 感知到连接开启  onopen
        socket.onopen = function (even) {
            var rt = document.getElementById('responseBody');
            rt.value = '连接开始了...'
        }
        // 感知到连接关闭  onclose
        socket.onclose = function (even) {
            var rt = document.getElementById('responseBody');
            rt.value = rt.value + '\n' + "连接关闭了...";
        }


    } else {
        alert('当前浏览器不支持WebSocket');
    }

    // 发送消息到服务器
    function send(message) {
        // 先判断socket是否创建好
        if (!window.socket) {
            return;
        }
        if (socket.readyState == WebSocket.OPEN){
            // 通过socket发送消息
            socket.send(message);
        } else {
            alert('连接没有开启')
        }
    }
</script>
    <form onsubmit="return false">
        <textarea name="message" style="height: 300px; width: 300px"></textarea>
        <input type="button" value="发送消息" onclick="send(this.form.message.value)">
        <textarea id="responseBody" style="height: 300px; width: 300px"></textarea>
        <input type="button" value="清空内容" onclick="document.getElementById('responseBody').value=''">
    </form>
</body>
</html>